package org.gstreamer.java.runtime;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class PathUtils {
	
	public enum Location {
		FIRST,
		LAST;
	}
		
	public static String addToPathChain(String theChain, String newSegment, String separator, boolean forceRelocate, Location location){
		if (theChain == null || theChain.equals("")){
			return newSegment;
		}
		String resultChain = null;
		List<String> list = parsePathChain(theChain, separator);
		if (list.contains(newSegment)){
			if (forceRelocate) {
				resultChain = removeFromPathChain(theChain, newSegment, separator);
			}else{
				return theChain;
			}
		}else{
			resultChain = theChain;
		}
		switch (location) {
			case FIRST:
				resultChain = newSegment + separator + resultChain;
				break;
			case LAST:
				resultChain = resultChain + separator + newSegment;
				break;
		}
		return resultChain;
	}
	
	public static String removeFromPathChain(String theChain, String segment, String separator){
		String result = null;
		List<String> list = parsePathChain(theChain, separator);
		boolean wasThere = false;
		// remove all existing segments from the chain
		while(list.contains(segment)){
			list.remove(segment);
			wasThere = true;
		}
		if (wasThere){
			for (String s : list) {
				result = result == null ? s : result + separator + s;
			}
		}else{
			result = theChain;
		}
		return result;
	}
	
	public static List<String> parsePathChain(String theChain, String separator) {
		List<String> output = new ArrayList<String>();
		StringTokenizer tokenizer = new StringTokenizer(theChain, separator);
		while(tokenizer.hasMoreTokens()){
			output.add(tokenizer.nextToken());
		}
		return output;
	}
}
